﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace com.zhongjh.Library.Common
{
    [AttributeUsage(AttributeTargets.Class)]
    public class ErrorAttribute : Attribute
    {
        private static bool m_blnIsWrite = true;
        private static bool m_blnIsInit = false;

        public ErrorAttribute()
        {
            if (m_blnIsWrite && !m_blnIsInit)
            {
                //处理未捕获的异常
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                m_blnIsInit = true;
            }
        }

        public ErrorAttribute(bool p_blnIsWrite)
            : this()
        {
            m_blnIsWrite = p_blnIsWrite;
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            Error.AppendException(ex);
            Error.WriteErrorLog();
        }

        void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            Error.AppendException(ex);
            Error.WriteErrorLog();
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            Error.WriteErrorLog();
        }
    }
}
